package db

import (
	"matrix/backend/db/mysql"
	"matrix/backend/util"
)

// Register : 用户注册
func Register(userName, userPwd string) (status int8) {
	status = 0
	// 生成token
	token, err := util.GenerateToken(userName, userPwd)
	if err != nil {
		status = 1
	}
	realPwd, _ := util.EnPwdCode([]byte(userPwd))
	// 插入用户信息
	stmt, err := mysql.DBConn().Prepare("INSERT tbl_user set user_name=?,user_pwd=?,user_token=?")
	_, err = stmt.Exec(userName, realPwd, token)
	if err != nil {
		status = 2
	}
	var table string = `CREATE TABLE  ` + userName + ` (
		id int NOT NULL AUTO_INCREMENT,
		parent_path varchar(1024) NOT NULL,
		file_name varchar(1024) NOT NULL,
		file_sha1 varchar(64) NOT NULL DEFAULT '',
		file_size bigint DEFAULT '0',
		category int DEFAULT '0',
		upload_at datetime DEFAULT CURRENT_TIMESTAMP,
		change_time datetime DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
		ext1 int DEFAULT 0,
		ext2 text,
		PRIMARY KEY (id)
	  ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci `
	if status == 0 {
		// 创建用户文件表
		stmt, err := mysql.DBConn().Prepare(table)
		if err != nil {
			status = 3
		} else {
			_, err = stmt.Exec()
			if err != nil {
				status = 4
			}
		}
	}
	// 返回状态码
	return status
}
